package com.uiotsoft.small.host.sampler.simple;

import com.uiotsoft.small.config.APPConfig;
import com.uiotsoft.small.mqtt.MqttClientHive;
import com.uiotsoft.small.mqtt.MqttClientOld;
import com.uiotsoft.util.encrypt.MD5Utils;
import com.uiotsoft.util.encrypt.small.SignUtil;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HostConnectSampler2 extends AbstractJavaSamplerClient {
    private volatile MqttClientHive clientNew;
    private static final Logger log = LoggerFactory.getLogger(HostConnectSampler2.class);
    private String subTopic;
    private MqttConnectOptions options;
    private String sn;

    public Arguments getDefaultParameters() {
        Arguments params = new Arguments();
        params.addArgument("appey", "${appkey}");
        params.addArgument("appsecret", "${appsecret}");
        params.addArgument("mqttUrl", "${mqttUrl}");
        params.addArgument("username", "${appkey}|${sn}|host|${__time(/1000,)}");
        params.addArgument("sn", "${sn}");
        params.addArgument("willTopic", "");
        params.addArgument("willData", "");
        return params;
    }

    private void setupValues(JavaSamplerContext context) {
        String appKey = context.getParameter("appey");
        String appSecret = context.getParameter("appsecret");
        String mqttUrl = context.getParameter("mqttUrl");
        String username = context.getParameter("username");
        sn = context.getParameter("sn");
        String willTopic = context.getParameter("willTopic");
        String willData = context.getParameter("willData");
        String clientId = "host-"+sn;
        subTopic = "host/+/+/" + sn + "/+";
        String password_new = MD5Utils.MD5Encoding(username + appSecret, "");
        clientNew = new MqttClientHive(mqttUrl,clientId,username,password_new);
        clientNew.setTopic(subTopic);
        clientNew.setAppKey(appKey);
        clientNew.setAppSecret(appSecret);
        //设置遗嘱
        if (willTopic != null && !willTopic.equals("")){
            if (appSecret != null && !appSecret.equals("")){
                byte[] message = SignUtil.getPublishMessage(willData, APPConfig.CHK_appKey,APPConfig.CHK_appSecret);
                clientNew.setWillTopic(willTopic);
                clientNew.setWillData(message);
            }else {
                log.error("appsecret 为空！");
            }
        }
    }

    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        setupValues(javaSamplerContext);
        JMeterVariables vars = JMeterContextService.getContext().getVariables();
        SampleResult results = new SampleResult();
        results.sampleStart();
        clientNew.connect();
        results.sampleEnd();
        if (clientNew != null){
            log.info("Connected client: "+clientNew.getClientId());
            log.info("Connected client: "+clientNew.getClientId());
            log.info("Connected client: "+clientNew.toString());
            String pubTopic1 = "common/host/mqttConnect/testsn00001900000000119000000001/hostLineState";
            String sendMsg1 = "{\"header\":{\"params\":{},\"identity\":\"testsn00001900000000119000000001\",\"msgId\":\"0\",\"appkey\":\"788916ea524bd1b6\",\"version\":\"1.0\",\"isEncrypt\":\"true\",\"compression\":\"none\",\"clientType\":\"host\",\"userUnique\":\"\"},\"payload\":{\"sn\":\"testsn00001900000000119000000001\",\"lineState\":\"online\"}}";
            clientNew.publish(pubTopic1, sendMsg1);

            String pubTopic = "cloud/host/dataSync/testsn00001900000000119000000001/syncFloor";
            long time = System.currentTimeMillis();
            String sendMsg = "{\"payload\":{\"code\":0,\"data\":{\"floorList\":[{\"floorId\":1,\"orderNum\":10,\"floorName\":\"testFloor1\"},{\"floorId\":2,\"orderNum\":10,\"floorName\":\"testFloor2\"},{\"floorId\":3,\"orderNum\":10,\"floorName\":\"testFloor3\"},{\"floorId\":4,\"orderNum\":10,\"floorName\":\"testFloor4\"},{\"floorId\":5,\"orderNum\":10,\"floorName\":\"testFloor5\"},{\"floorId\":6,\"orderNum\":10,\"floorName\":\"testFloor6\"},{\"floorId\":7,\"orderNum\":10,\"floorName\":\"testFloor7\"}],\"sn\":\"testsn00001900000000119000000001\"},\"desc\":\"\"},\"header\":{\"clientType\":\"host\",\"identity\":\"testsn00001900000000119000000001\",\"msgId\":\""+time+"\",\"appkey\":\"appke19000000001\",\"userUnique\":\"\",\"params\":{},\"compression\":\"none\",\"version\":\"1.0\",\"isEncrypt\":\"true\"}}";
            clientNew.publish(pubTopic, sendMsg);

            vars.putObject("clientOldHostNew", clientNew);
            results.setSuccessful(true);
            results.setResponseData("Successful", "UTF-8");
            results.setResponseMessage("Connection established successfully.");
            results.setResponseCodeOK();
        }else {
            results.setSuccessful(false);
            results.setResponseData("Connect failed", "UTF-8");
            results.setResponseMessage("Failed to establish Connection.");
            results.setResponseCode("501");
        }
        return results;
    }

}
